package com.example.spring_forum.controller;


import com.example.spring_forum.common.AppResult;
import com.example.spring_forum.common.ResultCode;
import com.example.spring_forum.config.AppConfig;
import com.example.spring_forum.exception.model.User;
import com.example.spring_forum.services.IUserService;
import com.example.spring_forum.utils.MD5Utils;
import com.example.spring_forum.utils.StringUtils;
import com.example.spring_forum.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult  register(@ApiParam("用户名")@RequestParam("username") @NonNull String username,
                               @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                               @ApiParam("密码") @RequestParam("password") @NonNull String password,
                               @ApiParam("确认密码")@RequestParam("passwordRepeat")@NonNull String passwordRepeat){

        //先校验用户注册两次输入的密码是否一致
        if(!password.equals(passwordRepeat)){
            //返回错误
            return AppResult.failed(ResultCode. FAILED_TWO_PWD_NOT_SAME );
        }

        //构造用户对象
        User user=new User();
        user.setUsername(username);//用户名
        user.setNickname(nickname);//昵称
        user.setPassword(password);//密码

        //加密密码
        //1.生成盐
        String salt= UUIDUtils.UUID_32();
        //2.生成密码的密文
        String encryptPassword= MD5Utils.md5Salt(password,salt);
        //3.设置密码和盐
        user.setPassword(encryptPassword);
        user.setSalt(salt);

        //调用service
        userService.createNormalUser(user);

        return AppResult.success("注册成功");
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return AppResult
     */
    @ApiParam("用户登录")
    @ResponseBody
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username")@NonNull String username,
                           @ApiParam("密码")@RequestParam("password") @NonNull String password){

       //调用service
        User user=userService.login(username,password);
        //将用户登录信息保存在session中
        //1.获取session对象
        HttpSession session=request.getSession(true);
        //2.把用户信息保存在session中
        session.setAttribute(AppConfig.SESSION_USER_KRY,user);

        return AppResult.success("登录成功");

    }

    @ApiOperation("用户退出")
    @ResponseBody
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
      //获取session
      HttpSession session=request.getSession(false);
      if(session!=null){
          log.debug(session.toString());
          //如果有session直接注销退出登录
          session.invalidate();
      }
      return AppResult.success("注销成功");

    }
    @ApiOperation("获取用户信息")
    @ResponseBody
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,@ApiParam("用户id") @RequestParam(value = "id",required = false) Long id){
        //定义返回的用户对象                                                                   //id是非必传参数
        User user;
         //根据用户传入的id获取用户对象的方式
        if(id == null){
            //获取session
            HttpSession session = request.getSession(false);
            //从session中获取用户对象
            user=(User)session.getAttribute(AppConfig.SESSION_USER_KRY);
        }else{

            user=userService.selectById(id);
        }


        //返回结果
        return AppResult.success(user);

    }

    /**
     * 修改个人信息
     * @param username 用户名(用于登录)
     * @param nickname 昵称
     * @param gender 性别
     * @param email 邮箱
     * @param phoneNum 电话
     * @param remark 个人简介
     * @return AppResult<User>
     */
    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult<User> modifyInfo (HttpServletRequest request,
                                       @ApiParam("用户名(用于登录)") @RequestParam(value = "username", required = false) String username,
                                       @ApiParam("昵称") @RequestParam(value = "nickname", required = false) String nickname,
                                       @ApiParam("性别") @RequestParam(value = "gender", required = false) Byte gender,
                                       @ApiParam("邮箱") @RequestParam(value = "email", required = false) String email,
                                       @ApiParam("电话") @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                       @ApiParam("个人简介") @RequestParam(value = "remark", required = false) String remark) {
        // 校验参数不能全部为空
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(nickname)
                && StringUtils.isEmpty(email) && StringUtils.isEmpty(phoneNum)
                && StringUtils.isEmpty(remark) && gender == null) {
            // 返回提示
            return AppResult.failed("要修改的信息不能为空");
        }
        // 获取用户Id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.SESSION_USER_KRY);

        // 构造User对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户Id
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setEmail(email); // 邮箱
        updateUser.setRemark(remark); // 个人简介

        // 调用Service
        userService.modifyInfo(updateUser);
        // 查询修改后的用户数据
        user = userService.selectById(user.getId());
        // 把User对象设置回session
        session.setAttribute(AppConfig.SESSION_USER_KRY, user);
        // 返回更新后的User对象
        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword (HttpServletRequest request,
                                     @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                     @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                     @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        // 新密码与确认密码必须相等
        if (newPassword.equals(passwordRepeat) == false) {
            // 返回提示
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.SESSION_USER_KRY);
        // 调用Service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        // 销毁当前的session
        session.invalidate();
        // 返回结果
        return AppResult.success();
    }


}
